<template>
	<view class="create-goods-container">
		<view class="top">扫描到{{ quantity }}个商品</view>
		<scroll-view scroll-y class="grid">
			<!-- <uni-forms :rules="rules" ref="formRef" :model="form"> -->
			<view class="goods-cateory-item" v-for="(ele, index) in createList" :key="ele.cName">
				<view class="cateory flex-center">
					<input
						placeholder="请输入分类名称"
						v-if="ele.flag || !ele.cName"
						class="edit-view"
						:class="{ 'gray-border': item.name, 'red-border': !item.name }"
						v-model="ele.cName"
					/>
					<view v-else style="flex: 1; font-size: 26rpx">{{ ele.cName }}</view>
					<view v-if="ele.flag || !ele.cName" style="margin-right: 10rpx; margin-left: 20rpx" @click="onSave('cateory', index)">
						<u-icon size="18" name="checkmark-circle-fill"></u-icon>
					</view>
					<view v-else style="margin-right: 10rpx" @click="onEdit('cateory', index)">
						<u-icon size="18" name="edit-pen"></u-icon>
					</view>
					<view @click="onDelete('cateory', index)" v-if="createList.length > 1"><u-icon size="18" name="trash-fill"></u-icon></view>
				</view>

				<view class="goods bg-white">
					<view class="goods-item flex" style="margin-top: 20rpx" v-for="(item, ind) in ele.dishes" :key="item.img">
						<!-- @click="onImagePreview(item.img, index, ind)" -->
						<image
							@click="handleImageTap(item.img, index, ind)"
							:style="{ border: item.img ? '2rpx solid transparent' : '2rpx solid #cfb0b5' }"
							:src="item.img ? item.img : require('@/static/images/classify/imgs.png')"
							style="width: 160rpx; height: 160rpx; border-radius: 8rpx"
							mode=""
						></image>
						<!-- <image v-else src="" style="width: 160rpx; height: 160rpx; border-radius: 8rpx" mode=""></image> -->
						<view class="goods-info">
							<view class="flex-center">
								<!-- <view class="edit-view" v-if="false">{{ item.name }}</view> -->
								<input class="edit-view" :class="{ 'gray-border': item.name, 'red-border': !item.name }" v-model="item.name" />
								<view style="margin-left: 10rpx" @click="onDelete('goods', index, ind)"><u-icon size="18" name="trash-fill"></u-icon></view>
							</view>

							<view class="flex-center" style="margin-top: 20rpx" v-if="item.specs.length < 2">
								<!-- <view class="goods-price edit-view flex justify-between">
									<view class="">30</view>
									<view style="color: #999">元</view>
								</view> -->

								<input
									type="text"
									:class="{ 'gray-border': item.specs[0].price, 'red-border': !item.specs[0].price }"
									class="edit-view"
									v-model="item.specs[0].price"
								/>
								<view style="color: #999; margin-left: 10rpx; margin-right: 10rpx" v-if="item.specs[0].specName">{{ item.specs[0].specName }}</view>
								<view style="color: #999; margin-left: 10rpx">元</view>
								<!-- <view @click="onEdit('goods', index, ind)" style="margin-left: 10rpx"><u-icon size="18" name="edit-pen"></u-icon></view> -->
							</view>

							<view v-else>
								<view class="spec flex-center" style="margin-top: 10rpx">
									<view class="edit-view" style="margin-right: 10rpx; background: #fff">规格</view>
									<view class="edit-view" style="margin-right: 10rpx; background: #fff">价格（元）</view>
									<view @click="onEdit('goods', index, ind)" style="margin-left: 10rpx"><u-icon size="18" name="edit-pen"></u-icon></view>
								</view>

								<view class="spec flex-center" style="margin-top: 10rpx" v-for="(v, i) in item.specs" :key="i">
									<input :class="{ 'gray-border': v.specName, 'red-border': !v.specNam }" class="edit-view" style="margin-right: 10rpx" v-model="v.specName" />
									<input :class="{ 'gray-border': v.price, 'red-border': !v.price }" class="edit-view" style="margin-right: 10rpx" v-model="v.price" />
									<!-- <view class="edit-view" style="margin-right: 10rpx">大份</view>
									<view class="edit-view" style="margin-right: 10rpx">30</view> -->
									<view @click="onDelete('spec', index, ind, i)" style="margin-left: 10rpx"><u-icon size="18" name="close-circle"></u-icon></view>
								</view>

								<!-- <view class="spec flex-center" style="margin-top: 20rpx">
									<view class="edit-view" style="margin-right: 10rpx">大份</view>
									<view class="edit-view" style="margin-right: 10rpx">30</view>
									<view style="margin-left: 10rpx"><u-icon size="18" name="close-circle"></u-icon></view>
								</view> -->
							</view>

							<view class="price"></view>
						</view>
					</view>
				</view>
				<view style="height: 60rpx; justify-content: center" class="bg-white flex-center" @click="addGoods(index)">
					<u-icon name="plus-circle" label="该分类下添加商品" color="#445F85" labelColor="#445F85" label-size="12" space="5"></u-icon>
				</view>
			</view>

			<!-- </uni-forms> -->
		</scroll-view>

		<view class="bottom">
			<button class="start-btn" @click="saveBtn" :disabled="btnDisabled">保存</button>
			<!-- 编辑商品 -->
			<u-popup :show="show" mode="bottom" round="10" @close="show = false">
				<view style="padding-bottom: 40rpx" class="popup">
					<view class="popup-title flex-center">
						<view class="text-gray">取消</view>
						<view class="popup-name">编辑商品</view>
						<view class="bg-white">确定</view>
					</view>
					<hr color="aaaaaa" />

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>商品名称</text>
							<text class="text-red" style="margin-left: 8rpx">*</text>
						</view>

						<input class="flex1" placeholder="请输入商品名称" value="椒盐排条" />
					</view>

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>商品分类</text>
							<text class="text-red" style="margin-left: 8rpx; margin-top: 8rpx">*</text>
						</view>

						<text class="flex1">椒盐排条</text>
						<u-icon name="arrow-right"></u-icon>
					</view>

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>价格（元）</text>
							<text class="text-red" style="margin-left: 8rpx">*</text>
						</view>

						<text class="flex1">椒盐排条</text>
					</view>

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>商品规格</text>
						</view>

						<text class="flex1">￥42/椒盐排条、￥45/蜜黄排条</text>
						<u-icon name="arrow-right"></u-icon>
					</view>

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>商品口味做法</text>
						</view>

						<text class="flex1 text-gray" v-if="true">待添加</text>
						<!-- 没有数据显示灰色 -->

						<u-icon name="arrow-right"></u-icon>
					</view>

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>商品加料</text>
						</view>

						<text class="flex1 text-gray" v-if="true">待添加</text>
						<!-- 没有数据显示灰色 -->
						<u-icon name="arrow-right"></u-icon>
					</view>

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>商品原料</text>
						</view>

						<text class="flex1 text-gray" v-if="true">待添加</text>
						<!-- 没有数据显示灰色 -->
						<u-icon name="arrow-right"></u-icon>
					</view>

					<view class="border-gray popup-item flex-center" style="height: 80rpx; padding: 0 30rpx">
						<view style="width: 200rpx" class="size-12">
							<text>商品描述</text>
						</view>

						<text class="flex1 text-gray" v-if="true">待添加</text>
						<!-- 没有数据显示灰色 -->
						<u-icon name="arrow-right"></u-icon>
					</view>
				</view>
			</u-popup>
		</view>
		<u-toast ref="uToast" />
	</view>
</template>

<script>
import imgNone from '@/static/images/classify/imgs.png';
import { mapState, mapMutations } from 'vuex';
export default {
	data() {
		return {
			createList: [],
			quantity: 0,
			show: false,
			currentGoods: {},
			hasEmpty: false,
			btnDisabled: false,

			lastTapTime: 0, // 上一次点击时间戳
			lastTapIndex: -1, // 上一次点击的分类索引
			lastTapDishIndex: -1, // 上一次点击的菜品索引

			popupData: {}
		};
	},
	computed: {
		...mapState('recognition', ['currentGoodsVuex'])
	},
	onLoad({ createList }) {
		if (createList != null && createList != undefined) {
			try {
				this.createList = JSON.parse(decodeURIComponent(createList));
				this.createList.forEach((item) => {
					// item.flag = false;
					this.$set(item, 'flag', false);
				});
				this.quantity = this.createList.reduce((acc, num) => acc + num.dishes.length, 0);
			} catch (e) {
				console.error('JSON 解析失败：', e);
				this.createList = []; // 设默认值，避免页面崩溃
			}
		}
	},
	onShow() {
		const that = this;
		if (that.currentGoodsVuex.from) {
			that.createList = JSON.parse(JSON.stringify(that.currentGoodsVuex.createList));
			this.quantity = this.createList.reduce((acc, num) => acc + num.dishes.length, 0);
			this.setCurrentGoods({
				index: 0,
				ind: 0,
				imageUrl: '',
				foodName: '',
				from: '',
				createList: [],
				foodList: [],
				form: {}
			});
		}
	},
	methods: {
		...mapMutations('recognition', ['setCurrentGoods']),
		// 保存
		async saveBtn() {
			this.hasEmpty = false;
			this.hasEmpty = this.createList.some(
				(cateory) =>
					!cateory.cName ||
					cateory.dishes.some((goods) =>
						// !goods.img ||
						!goods.name || goods.specs.length > 1 ? goods.specs.some((spec) => !spec.price || !spec.specName) : !goods.specs[0].price
					)
			);
			if (this.hasEmpty) {
				this.$refs.uToast.show({ type: 'error', message: '保存失败，数据存在空项' });
				console.log('数据存在空项，终止操作');
			} else {
				this.btnDisabled = true;
				this.$api
					.createGoodsListAPI(this.createList)
					.then((res) => {
						this.$refs.uToast.show({
							type: 'success',
							message: '导入成功',
							complete: () => {
								uni.reLaunch({
									url: '/pages/workbench/recognition/list'
								});
							}
						});
					})
					.catch((err) => {
						console.log(err);
					})
					.finally(() => {
						this.btnDisabled = false;
					});
			}
		},
		// 添加商品
		addGoods(index) {
			this.createList[index].dishes.push({
				name: '',
				img: '',
				specs: [
					{
						specName: '',
						price: ''
					}
				]
			});
		},
		onDelete(type, index, ind, i) {
			console.log(type, index, ind, i);
			if (type === 'cateory') {
				this.createList.splice(index, 1);
			} else if (type === 'goods') {
				this.createList[index].dishes.splice(ind, 1);
			} else {
				this.createList[index].dishes[ind].specs.splice(i, 1);
			}
		},
		onEdit(type, index, ind, i) {
			console.log(type, index, ind, i);
			if (type === 'cateory') {
				this.createList[index].flag = true;
			} else if (type === 'goods') {
				this.show = true;
				// 将数据传入
			} else {
			}
		},
		onSave(type, index) {
			if (this.createList[index].cName) {
				this.createList[index].flag = false;
			} else {
			}
		},
		onImagePreview(url, index, ind) {
			// 图片双击查看
			uni.previewImage({
				current: url,
				urls: this.createList.flatMap((item) => {
					return item.dishes.map((e) => e.img);
				})
			});
		},
		imageDoubleClick(imageUrl, index, ind) {
			uni.showActionSheet({
				itemList: ['删除', '修改'],
				itemColor: '',
				//成功时回调
				success: (res) => {
					if (!res.cancel) {
						console.log(res);
						if (!res.tapIndex) {
							// 删除
							this.createList[index].dishes[ind].img = null;
						} else {
							// 修改 😒😒😒😒
							uni.navigateTo({
								url: `/pages/workbench/recognition/checkedImage`
							});
							this.setCurrentGoods({
								index,
								ind,
								imageUrl,
								foodName: this.createList[index].dishes[ind].name,
								from: '/pages/workbench/recognition/createGoods',
								createList: this.createList,
								foodList: [],
								form: {}
							});
						}
					}
				}
			});
		},
		// 统一处理点击事件
		handleImageTap(imgUrl, index, ind) {
			if (imgUrl) {
				// 判断当前有没有图片
				const currentTime = Date.now();
				// 判断是否为双击（300ms 内连续点击同一项）
				if (currentTime - this.lastTapTime < 300 && index === this.lastTapIndex && ind === this.lastTapDishIndex) {
					// 触发双击操作
					// 重置记录
					this.onImagePreview(imgUrl, index, ind);

					this.lastTapTime = 0;
					this.lastTapIndex = -1;
					this.lastTapDishIndex = -1;
				} else {
					// 单击时延迟触发预览（等待可能出现的双击）
					setTimeout(() => {
						if (this.lastTapTime !== 0) {
							this.imageDoubleClick(imgUrl, index, ind);
						}
					}, 300);
					// 记录当前点击信息
					this.lastTapTime = currentTime;
					this.lastTapIndex = index;
					this.lastTapDishIndex = ind;
				}
			} else {
				// 没有图片直接选图片😒😒😒😒
				uni.navigateTo({
					url: `/pages/workbench/recognition/checkedImage`
				});
				this.setCurrentGoods({
					index,
					ind,
					imageUrl: imgUrl,
					foodName: this.createList[index].dishes[ind].name,
					from: '/pages/workbench/recognition/createGoods',
					createList: this.createList,
					foodList: [],
					form: {}
				});
			}
		}
	}
};
</script>

<style lang="scss" scoped>
.create-goods-container {
	height: 100vh;
	background-color: #f7f8fa;
	display: flex;
	flex-direction: column;
	box-sizing: border-box;
	.top {
		line-height: 80rpx;
		padding-left: 20rpx;
		background-color: #fefbe8;
	}
	.grid {
		overflow-y: hidden;
		// height: calc(100vh -200rpx);
		width: calc(100% - 40rpx);
		display: flex;
		flex-direction: column;
		margin: 0 20rpx;
		padding: 10rpx 20rpx;
		border-radius: 10rpx;
		flex: 1;
		box-sizing: border-box;
		.goods-cateory-item {
			margin-top: 20rpx;
			.cateory {
			}
			.goods {
				margin-top: 20rpx;
				padding: 20rpx;
				border-radius: 8rpx;
				.goods-item {
					.goods-info {
						flex: 1;
						margin-left: 10rpx;
						.goods-name {
						}
					}
				}
			}
		}
	}
	.bottom {
		height: 120rpx;
		background: white;
		.start-btn {
			width: 80%;
			height: 80rpx;
			margin: 20rpx auto;
			background-color: $color-primary;
			border-radius: 40rpx;
			line-height: 80rpx;
			color: #fff;
			font-size: 28rpx;
		}
	}
}

.edit-view {
	flex: 1;
	height: 60rpx;
	font-size: 24rpx;
	line-height: 60rpx;
	padding-left: 20rpx;
	border-radius: 6rpx;
	padding-right: 20rpx;
}

.red-border {
	background-color: #f7f8fa;
	border: 2rpx solid #cfb0b5;
}
.gray-border {
	background-color: #f7f8fa;
	border: 2rpx solid transparent;
}
.popup {
	.popup-title {
		padding: 20rpx;
		.popup-name {
			flex: 1;
			text-align: center;
			font-size: 32rpx;
			font-weight: bold;
		}
	}
	.size-12 {
		font-size: 24rpx;
	}
}

.action-buttons {
	z-index: 9999999;
	position: fixed;
	bottom: 0;
	left: 0;
	right: 0;
	display: flex;
	justify-content: space-around;
	padding: 10rpx;
	background: rgba(0, 0, 0, 0.5);
}
</style>
